package com.sz.admin.datainfo.controller;

import com.sz.admin.datainfo.pojo.dto.DriverUserCreateDTO;
import com.sz.admin.datainfo.pojo.dto.DriverUserUpdateDTO;
import com.sz.admin.datainfo.pojo.dto.DriverUserListDTO;
import com.sz.admin.datainfo.pojo.dto.DriverVehicleQueryDTO;
import com.sz.admin.datainfo.pojo.vo.DriverUserVO;
import com.sz.admin.datainfo.pojo.vo.DriverVehicleInfoVO;
import com.sz.admin.datainfo.service.DriverUserService;
import com.sz.core.common.entity.ApiPageResult;
import com.sz.core.common.entity.ApiResult;
import com.sz.core.common.entity.PageResult;
import com.sz.core.common.entity.SelectIdsDTO;
import com.sz.core.common.constant.GlobalConstant;
import com.sz.core.common.enums.CommonResponseEnum;
import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 司机用户管理 前端控制器
 * </p>
 *
 * @author sz-admin
 * @since 2025-09-12
 */
@Tag(name = "司机用户管理")
@RestController
@RequestMapping("/driver-user")
@RequiredArgsConstructor
public class DriverUserController {

    private final DriverUserService driverUserService;

    @Operation(summary = "添加司机用户")
    @SaCheckPermission(value = "driver.user.create_btn", orRole = GlobalConstant.SUPER_ROLE)
    @PostMapping
    public ApiResult<Void> create(@Valid @RequestBody DriverUserCreateDTO dto) {
        driverUserService.create(dto);
        return ApiResult.success();
    }

    @Operation(summary = "修改司机用户")
    @SaCheckPermission(value = "driver.user.update_btn", orRole = GlobalConstant.SUPER_ROLE)
    @PutMapping
    public ApiResult<Void> update(@Valid @RequestBody DriverUserUpdateDTO dto) {
        driverUserService.update(dto);
        return ApiResult.success();
    }

    @Operation(summary = "查询分页列表")
    @SaCheckPermission(value = "driver.user.query_table", orRole = GlobalConstant.SUPER_ROLE)
    @GetMapping("/page")
    public ApiPageResult<PageResult<DriverUserVO>> page(DriverUserListDTO dto) {
        return ApiPageResult.success(driverUserService.page(dto));
    }

    @Operation(summary = "查询列表")
    @SaCheckPermission(value = "driver.user.query_table", orRole = GlobalConstant.SUPER_ROLE)
    @GetMapping("/list")
    public ApiResult<List<DriverUserVO>> list(DriverUserListDTO dto) {
        return ApiResult.success(driverUserService.list(dto));
    }

    @Operation(summary = "批量删除")
    @SaCheckPermission(value = "driver.user.delete_btn", orRole = GlobalConstant.SUPER_ROLE)
    @DeleteMapping
    public ApiResult<Void> remove(@Valid @RequestBody SelectIdsDTO dto) {
        driverUserService.remove(dto);
        return ApiResult.success();
    }

    @Operation(summary = "查询司机车辆信息及监控记录")
    @SaCheckPermission(value = "driver.user.query_table", orRole = GlobalConstant.SUPER_ROLE)
    @PostMapping("/vehicle-info")
    public ApiResult<PageResult<DriverVehicleInfoVO>> queryDriverVehicleInfo(@Valid @RequestBody DriverVehicleQueryDTO dto) {
        PageResult<DriverVehicleInfoVO> result = driverUserService.queryDriverVehicleInfo(dto);
        if (result == null || result.getRows().isEmpty()) {
            return ApiResult.error(CommonResponseEnum.NOT_EXISTS.message("该司机未关联任何车辆"));
        }
        return ApiResult.success(result);
    }

    @Operation(summary = "查询司机车辆信息及监控记录(通过URL参数)")
    @SaCheckPermission(value = "driver.user.query_table", orRole = GlobalConstant.SUPER_ROLE)
    @GetMapping("/vehicle-info")
    public ApiResult<PageResult<DriverVehicleInfoVO>> queryDriverVehicleInfoByParams(
            @RequestParam(required = false) Long driverId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit) {
        
        // 构建查询DTO
        DriverVehicleQueryDTO dto = new DriverVehicleQueryDTO();
        dto.setDriverId(driverId);
        
        // 处理时间参数
        if (startTime != null && !startTime.isEmpty()) {
            try {
                dto.setStartTime(LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            } catch (Exception e) {
                // 如果时间格式不正确，忽略该参数
            }
        }
        
        if (endTime != null && !endTime.isEmpty()) {
            try {
                dto.setEndTime(LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            } catch (Exception e) {
                // 如果时间格式不正确，忽略该参数
            }
        }
        
        // 设置分页参数
        dto.setPage(page);
        dto.setLimit(limit);
        
        PageResult<DriverVehicleInfoVO> result = driverUserService.queryDriverVehicleInfo(dto);
        if (result == null || result.getRows().isEmpty()) {
            return ApiResult.error(CommonResponseEnum.NOT_EXISTS.message("该司机未关联任何车辆"));
        }
        return ApiResult.success(result);
    }

    @Operation(summary = "详情")
    @SaCheckPermission(value = "driver.user.query_table", orRole = GlobalConstant.SUPER_ROLE)
    @GetMapping("/{id}")
    public ApiResult<DriverUserVO> detail(@PathVariable Long id) {
        return ApiResult.success(driverUserService.detail(id));
    }
}